package com.csyf.manager.utils;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.csyf.manager.entity.CardInfoVo;
import com.csyf.manager.exception.ApiValidateException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: casper
 * @Description: 文件工具类
 * @Date: Created in 2018/9/20 9:13
 */
@Slf4j
public class FileUtil {

    //上传文件
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{

        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    //读取excel文件
    public static List<CardInfoVo> readxls(String filePath) throws ApiValidateException {
        ImportParams params = new ImportParams();
        List<CardInfoVo> list = ExcelImportUtil.importExcel( new File(filePath), CardInfoVo.class, params);

        List<String> objects = new ArrayList<>();

        for (CardInfoVo ob : list) {
            if (objects.contains(ob.getMoney())) {
                throw new ApiValidateException(String.format("金额[%s]重复，规则不允许，请重新上传", ob.getMoney()));
            }
            objects.add(ob.getMoney());
        }

        String[] objects1 = objects.toArray(new String[objects.size()]);
        BigDecimal add = NumberHelpler.add(objects1);
        log.info("出款总金额为:{}", add);
        log.info("出款列表为:{}", list);
        return list;
    }

}
